package com.cn.wanxi.jwt.service.impl;

import com.cn.wanxi.jwt.domain.Permission;
import com.cn.wanxi.jwt.domain.User;
import com.cn.wanxi.jwt.mapper.PermissionMapper;
import com.cn.wanxi.jwt.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @ClassName UserDetialsServiceImpl
 * @Description TODO
 * @Author JiJiang
 * @Date 2022/9/27 14:08
 * @Version 1.0
 */
@Service
public class UserDetialsServiceImpl implements UserDetailsService {


    @Autowired
    UserMapper userMapper;


    @Autowired
    PermissionMapper permissionMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        System.out.println(username);


        //region dynamic

        //1.根据输入的用户名查询实际的用户信息  --->这里可能为null;
        User user = userMapper.selectByUsername(username);

        if (user == null) {
            return user;
        }
        //2.获取该用户的id
        long userId = user.getId();

        //3.根据id获取该用户的所有权限
        List<Permission> permissionSet = permissionMapper.selectByUserId((int) userId);

        //4.给user设置对应权限
        user.setAuthorities(permissionSet);

        //endregion

        return user;

    }
}
